package com.aceleeyy.sevenstar.controller;

import com.aceleeyy.sevenstar.config.ErrorMessage;
import com.aceleeyy.sevenstar.dao.MagazineMapper;
import com.aceleeyy.sevenstar.dao.SearchInfoMapper;
import com.aceleeyy.sevenstar.model.Magazine;
import com.aceleeyy.sevenstar.model.Result;
import com.aceleeyy.sevenstar.model.SearchInfo;
import com.aceleeyy.sevenstar.model.UserInfo;
import com.aceleeyy.sevenstar.utils.JacksonUtil;
import com.aceleeyy.sevenstar.utils.WXAuthUtil;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 搜索管理
 *
 * @auther: Ace Lee
 * @date: 2019/10/26 10:43
 */
@Api(value = "搜索管理", description = "搜索管理")
@Slf4j
@RestController
@RequestMapping("searchs")
public class SearchInfoController extends BaseController {

    @Value("${file.server.path}")
    private String serverPath;

    @Autowired
    private SearchInfoMapper searchInfoMapper;
    @Autowired
    private MagazineMapper magazineMapper;

    @ApiOperation(value = "搜索")
    @GetMapping("")
    public Result get(HttpServletRequest request, @RequestParam(value = "openid") String openid,
                      @RequestParam(value = "keyword")String keyword ) {
        Result result;
        log.info("搜索请求参数：{},{}", openid,keyword);
        if (StringUtils.isEmpty(openid)) {
            return Result.error(ErrorMessage.E_001.getErrDesc());
        }

        try {
            UserInfo userInfo = getUserByOpenid(openid);
            if (null==userInfo){
                return Result.error(ErrorMessage.E_004.getErrDesc());
            }

            if (StringUtils.isEmpty(keyword)) {
                List<Magazine> list = magazineMapper.selectAll();
                log.info("搜索结果：{}", CollectionUtils.isEmpty(list)?0:list.size());
                return new Result<>(list);
            }

            //先保存搜索记录
            SearchInfo searchInfo = new SearchInfo();
            searchInfo.setUserId(userInfo.getId());
            searchInfo.setCode(openid);
            searchInfo.setText(keyword);
            searchInfo.setCreatedTime(new Date());
            int add = searchInfoMapper.insertSelective(searchInfo);
            log.info("搜索保存记录结果：{}", add);
            //后查询结果
            List<Magazine> results = Lists.newArrayList();
            String url = serverPath+"/searchs?keyword="+keyword;
            log.info("搜索url:" + url);
            JSONObject jsonObject = WXAuthUtil.doGetJson(url);
            int code = jsonObject.getIntValue("code");
            if (0==code){
                String msg = jsonObject.getString("msg");
                results = JacksonUtil.json2Bean(msg, new TypeReference<List<Magazine>>() {});
            }
            log.info("搜索结果：{}", results.size());
            result = new Result<>(results);
        } catch (Exception e) {
            log.error("搜索异常：{}", Throwables.getStackTraceAsString(e));
            result = Result.error(ErrorMessage.E_999.getErrDesc());
        }
        return result;
    }

    @ApiOperation(value = "搜索历史")
    @GetMapping("/history")
    public Result getHistory(HttpServletRequest request, @RequestParam(value = "openid") String openid ) {
        Result result;
        log.info("搜索历史请求参数：{}", openid);
        if (StringUtils.isEmpty(openid)) {
            return Result.error(ErrorMessage.E_001.getErrDesc());
        }

        try {
            UserInfo userInfo = getUserByOpenid(openid);
            if (null==userInfo){
                return Result.error(ErrorMessage.E_004.getErrDesc());
            }

            List<SearchInfo> list = searchInfoMapper.selectByUserId(userInfo.getId());
            log.info("搜索历史结果：{}", CollectionUtils.isEmpty(list)?0:list.size());
            List<SearchInfo> unique = new ArrayList<>();
            if (!CollectionUtils.isEmpty(list)){
                //去重
                unique = list.stream().collect(
                        Collectors.collectingAndThen(
                                Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(SearchInfo::getText))), ArrayList::new)
                );
            }
            result = new Result<>(unique);
        } catch (Exception e) {
            log.error("搜索历史异常：{}", Throwables.getStackTraceAsString(e));
            result = Result.error(ErrorMessage.E_999.getErrDesc());
        }
        return result;
    }


    @ApiOperation(value = "清除搜索历史")
    @DeleteMapping("/history")
    public Result deleteHistory(HttpServletRequest request, @RequestParam(value = "openid") String openid ) {
        Result result;
        log.info("清除搜索历史请求参数：{}", openid);
        if (StringUtils.isEmpty(openid)) {
            return Result.error(ErrorMessage.E_001.getErrDesc());
        }

        try {
            UserInfo userInfo = getUserByOpenid(openid);
            if (null==userInfo){
                return Result.error(ErrorMessage.E_004.getErrDesc());
            }

            int delete = searchInfoMapper.deleteByUserId(userInfo.getId());
            log.info("清除搜索历史结果：{}", delete);
            result = new Result<>(delete);
        } catch (Exception e) {
            log.error("清除搜索历史异常：{}", Throwables.getStackTraceAsString(e));
            result = Result.error(ErrorMessage.E_999.getErrDesc());
        }
        return result;
    }


}
